#!/usr/bin/env python
# -*- coding:utf-8 -*-

'''通过点,面数据创建实体

历史:
    2018-03-17 YY 创建
'''

import bpy
import ezdxf
from bpy_extras.object_utils import object_data_add

def add_edges(name, verts, edges, location = None):
    bpy.ops.object.select_all(action = 'DESELECT')

    mesh = bpy.data.meshes.new(name)
    mesh.from_pydata(verts, edges, [])
    if mesh.name != name:
        mesh.name = name

    obj = bpy.data.objects.new(mesh.name, mesh)

    # Link object to scene and make active
    scene = bpy.context.scene
    scene.objects.link(obj)
    scene.objects.active = obj
    scene.update()
    obj.select = True

    bpy.ops.object.mode_set(mode="EDIT")
    bpy.ops.mesh.normals_make_consistent(inside=False)
    bpy.ops.mesh.edge_face_add()
    bpy.ops.object.mode_set(mode="OBJECT")
    if location:
        obj.location = location
    else:
        bpy.ops.object.origin_set(type='ORIGIN_GEOMETRY')




if __name__ == '__main__':
    try:
        bpy.ops.object.mode_set(mode="OBJECT")
    except:
        pass
    dwg = ezdxf.readfile(r'D:\Develop\GitRepos\BIM\blender\2018\data\test.dxf')
    modelspace = dwg.modelspace()
    find_types = 'POLYLINE'
    for index, e in enumerate(modelspace.query(find_types)):
        verts = list(e.points())
        #verts = [(0, 0, 0), (1, 0, 0), (1, 1, 0), (0, 1, 0)]
        edges = []
        for i in range(len(verts) - 1):
            edges.append((i, i + 1))
        edges.append((len(verts) - 1, 0))
        add_edges('dxf,%s' % index, verts, edges)